package org.kinglone.weixin.kit;

import java.io.IOException;
import java.util.Map;

import org.kinglone.basic.model.User;
import org.kinglone.basic.model.WeixinMenu;
import org.kinglone.basic.service.UserService;
import org.kinglone.basic.service.WeixinMenuService;
import org.kinglone.weixin.model.WeixinUser;
import org.kinglone.weixin.service.WeixinUserService;
import org.kinglone.weixin.web.servlet.BeanFactoryContext;

public class WeixinEventKit {

	public static String handlerEventMsg(Map<String, String> msgMap) throws IOException {
		String event = msgMap.get("Event");
		if("CLICK".equals(event)) {
			return handlerClickEvent(msgMap);
		}else if("subscribe".equals(event)) {
			//用户关注事件
			return handlerSubscribeEvent(msgMap);
		}else if("unsubscribe".equals(event)) {
			//取消关注
			return handlerUnsubscribeEvent(msgMap);
		}
		return null;
	}
	


	//取消关注
	private static String handlerUnsubscribeEvent(Map<String, String> msgMap) {
		String openid = msgMap.get("FromUserName");		
		UserService userService = (UserService)BeanFactoryContext.getService("userService");
		User u = userService.loadByOpenid(openid);
		if(u!=null) {
			u.setStatus(0);
			userService.update(u);
		}
		return null;
	}

	//用户关注事件
	private static String handlerSubscribeEvent(Map<String, String> msgMap) throws IOException {
		String openid = msgMap.get("FromUserName");
		UserService userService = (UserService)BeanFactoryContext.getService("userService");
		User u = userService.loadByOpenid(openid);
		if(u==null){
			WeixinUserService weixinUserService = (WeixinUserService)BeanFactoryContext.getService("weixinUserService");
			WeixinUser weixinUser = weixinUserService.queryByOpenid(openid);
			u = weixinUser.getUser();
			userService.add(u);
		}else{
			//用户存在就更新
			u.setStatus(1);
			userService.update(u);
		}
		if(u.getBind()==0) {
			String bindUrl = "http://1n723r6757.iok.la/weixin/user/bindExistUser";
			return WeixinMessageKit.map2xml(MessageCreateKit.createTextMsg(msgMap, "<a href=\""+bindUrl+"\">请点击绑定用户获得更好的体验</a>"));
		} else {
			String bindUrl = "http://www.kinglone.com";
			return WeixinMessageKit.map2xml(MessageCreateKit.createTextMsg(msgMap, "<a href=\""+bindUrl+"\">欢迎你再次使用我们的微信平台，点击打开我们的页面</a>"));
		}
	}

	private static String handlerClickEvent(Map<String, String> msgMap) throws IOException {
		String keyCode = msgMap.get("EventKey");
		WeixinMenuService weixinMenuService = (WeixinMenuService)BeanFactoryContext.getService("weixinMenuService");
		WeixinMenu wm = weixinMenuService.loadByKey(keyCode);
		if(wm!=null&&wm.getRespType()==1) {
			Map<String,Object> map = MessageCreateKit.createTextMsg(msgMap, wm.getContent());
			return WeixinMessageKit.map2xml(map);
		}
		return null;
	}

}
